package com.example.botechotext.util;

import com.alibaba.fastjson.JSONObject;
import com.example.botechotext.dto.AdditionalMessage;
import com.example.botechotext.dto.MessageRequest;
import com.example.botechotext.stream.EventProcessor;
import com.example.botechotext.stream.StreamEvent;
import com.example.botechotext.stream.UnsafeOkHttpClient;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class DingTalkPostRequest {

    private static final Logger log = LoggerFactory.getLogger(DingTalkPostRequest.class);

    @Value("${Personal_Access_Token}")
    private String personal_Access_Token;

    @Value("${Bot_Id}")
    private String bot_Id;

    @Value("${url}")
    private String url;

    @Value("${UserId:User123}")
    private String userId;

    @Autowired
    EventProcessor eventProcessor;

    private final OkHttpClient client = UnsafeOkHttpClient.getUnsafeOkHttpClient();

    public StringBuilder send(String args) throws IOException {
        List<AdditionalMessage> messages = Arrays.asList(new AdditionalMessage("user", args, "text"));
        MessageRequest messageRequest = new MessageRequest(bot_Id, userId, true, true, messages);
        String message = JSONObject.toJSONString(messageRequest);
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        StringBuilder responseStr = new StringBuilder("");
        RequestBody requestBody = RequestBody.create(message, JSON);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + personal_Access_Token)
                .post(requestBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response + ", Response body: " + response.body().string());
            }

            log.info("Response Code : {}", response.code());
            log.info("Response Headers: {}", response.headers().toString());

            int counter = 0;
            List<String> lines = new ArrayList<>();

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    log.info("Line: {}", line);
                    lines.add(line); // 将当前行添加到列表中

                    counter++;
                    if (counter % 3 == 0) { // 每三行调用一次 parseEvent
                        StreamEvent event = parseEvent(lines);
                        eventProcessor.processEvent(event, responseStr);
                        lines.clear(); // 清空列表，准备下一轮
                    }
                }

                // 处理剩余的行（如果有的话）
                if (!lines.isEmpty()) {
//                    StreamEvent event = parseEvent(lines);
//                    eventProcessor.processEvent(event ,responseStr);
                }
            } catch (IOException e) {
                // 处理异常
            } finally {
                response.body().close();
            }

// 注意：不要在try-with-resources块外部使用response.body().string()
// 因为body可能已经被读取或关闭了


            log.info("回复: {}", responseStr);
            return responseStr;

        }
    }

    private static StreamEvent parseEvent(List<String> lines) {
        String event = lines.get(0).split(":")[1];
        String[] parts = lines.get(1).split(":", 2);
        String data = parts[1];
        StreamEvent streamEvent = new StreamEvent();
        streamEvent.setEventType(event);
        streamEvent.setEventData(data);


        return streamEvent;
    }
}
